package com.yl.pay;

import com.yl.entity.Goods;
import com.yl.utils.UnionPayUtil;
import lombok.Data;
import lombok.extern.java.Log;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Data
@ConfigurationProperties(prefix = "wx-pay")
@Log
public class WxPay {
    //读取资源配置参数
    private String url;
    private String mid;
    private String tid;
    private String instMid;
    private String msgSrc;
    private String md5Key;
    private String msgType_refund;
    private String msgType_secureCancel;
    private String msgType_secureComplete;
    private String msgType_close;
    private String msgType_query;
    private String msgSrcId;
    private String msgType;
    private String notifyUrl;
    private String returnUrl;

    /**
     * 接收并处理下单请求
     *
     */
    public String publicPay(String merOrderId,String amount,String actName) throws Exception {
        log.info("#### wxPay amount = " + amount);
        String amou = String.valueOf(new Double(amount)*100D);
        amou = (amou.indexOf(".")>0)?amou.substring(0,amou.indexOf(".")):amou;
        long am = Long.parseLong(amou);
        // 准备商品信息
        List<Goods> goodsList = new ArrayList<Goods>();
        goodsList.add(new Goods(merOrderId.toString(), actName, 1L, am, "Auto", "goods body"));
        // 组织请求报文，具体参数请参照接口文档，以下仅作模拟
        JSONObject json = new JSONObject();
        json.put("mid", mid);
        json.put("tid", tid);
        json.put("msgType", msgType);
        json.put("msgSrc", msgSrc);
        json.put("instMid", instMid);

//        json.put("merOrderId", UnionPayUtil.genMerOrderId(msgSrcId));
        json.put("merOrderId", merOrderId);
        json.put("totalAmount", am);//实际支付价钱//1100
        //json.put("totalAmount", 200);//实际支付价钱//1100
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        json.put("goods", goodsList);
        json.put("notifyUrl", notifyUrl);
        json.put("returnUrl", returnUrl);

        json.put("secureTransaction", false);

        //json.put("sceneType", "AND_WAP");
        //json.put("merAppName", "全民付");
        //json.put("merAppId", "http://www.chinaums.com");
        json.put("signType", "SHA256");

        String urlPay = UnionPayUtil.makeOrderRequest(json,md5Key,url);
        return urlPay;
    }
}
